var n = 0; //存储图片加载到的位置，避免每次都从第一张图片开始遍历
var img = document.getElementsByTagName("img");
var num = img.length;

lazyload(); //页面载入完毕加载可是区域内的图片

//绑定事件 用防抖封装
window.onscroll = debounce(lazyload, 300);

function lazyload() {
  console.log("懒加载触发了！");
  //监听页面滚动事件
  var seeHeight = document.documentElement.clientHeight; //可见区域高度
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滚动条距离顶部高度
  for (var i = n; i < num; i++) {
    if (img[i].offsetTop < seeHeight + scrollTop) {
      img[i].src = img[i].getAttribute("data-src");
      n = i + 1;
    }
  }
}


function debounce(fn, delay) {
  let timer;
  return function () {
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, 300);
  };
}
